package com.fr.schedule.task;

import com.fr.fs.schedule.ScheduleContext;
import com.fr.general.ComparatorUtils;
import com.fr.general.FRLogger;
import com.fr.json.JSONArray;
import com.fr.json.JSONException;
import com.fr.json.JSONObject;
import com.fr.schedule.entry.SAPSynManager;
import com.fr.schedule.util.ScheduleLogUtils;
import com.fr.schedule.util.TaskConfig;
import com.fr.third.org.quartz.Scheduler;
import com.fr.third.org.quartz.SchedulerException;
import com.fr.third.org.quartz.Trigger;

public class SAPSynTask extends ItriggerTask {
	private static final long serialVersionUID = 1L;
	public static final String TABLE_NAME = "fr_schedule_sapsyn_task";
    private static FRLogger log = FRLogger.getLogger();
	private String transfers;

	
	public SAPSynTask() {
	}
	
	public SAPSynTask(TaskConfig taskConfig) {
        super(taskConfig);
		this.transfers = taskConfig.getTransfer();
	}
	
	public String getTransfers() {
		return transfers;
	}
	
	public String[] getTransferNames() {
		if (this.transfers != null) {
			try {
				JSONArray ja = new JSONArray(this.transfers);
				String[] names = new String[ja.length()];
				for (int i = 0; i < ja.length(); i++) {
					names[i] = ja.getString(i);
				}
				
				return names;
			} catch (JSONException e) {
                ScheduleLogUtils.error(e);
				return null;
			}
		}
		
		return null;
	}

	public void setTransfers(String transfers) {
		this.transfers = transfers;
	}
	
    public JSONObject createJSONConfig() throws JSONException {
		JSONObject jo = new JSONObject();
		super.createJSONConfig(jo);
		
		jo.put("transfers", new JSONArray(transfers));
		
		return jo;
	}

	protected void setTriggerState(JSONObject jo) throws JSONException {
		try {
			Scheduler scheduler  = ScheduleContext.getScheduler();
			Trigger[] triggers = scheduler.getTriggersOfJob(getName(), SAPSynManager.SAPSYN_GROUP_NAME);
			if(triggers.length > 0){
				Trigger trigger = triggers[0];
				int triggerState = scheduler.getTriggerState(trigger.getName(), trigger.getGroup());
				jo.put("state", triggerState);
			}
		} catch (SchedulerException e) {
            ScheduleLogUtils.error(e);
		}
	}
	
	public boolean equals(Object obj) {
		if(!(obj instanceof ScheduleTask)) {
			return false;
		}
		
		SAPSynTask task = (SAPSynTask)obj;
		
		return super.equals(obj)
		&& ComparatorUtils.equals(this.transfers, task.transfers);
	}

	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}
